package com.app.ytong.manager.in;

import android.content.Context;
import android.os.Build;
import android.text.TextUtils;
import android.view.View;

import androidx.annotation.RequiresApi;
import androidx.fragment.app.FragmentActivity;
import androidx.viewpager.widget.ViewPager;

import com.app.ytong.R;
import com.app.ytong.basis.Constants;
import com.app.ytong.bean.BasisBean;
import com.app.ytong.bean.GoodsListBean;
import com.app.ytong.bean.GoodsListData;
import com.app.ytong.bean.GoodsSubmitBean;
import com.app.ytong.bean.LoginBean;
import com.app.ytong.bean.MenuBean;
import com.app.ytong.bean.SupplierListData;
import com.app.ytong.bean.TraceListData;
import com.app.ytong.greendao.GreenDaoUtils;
import com.app.ytong.manager.qing.ScaleActivity;
import com.app.ytong.multiselection.TypeLabelGridLayout;
import com.app.ytong.util.MyUtils;
import com.app.ytong.util.UnitUtil;
import com.caysn.autoreplyprint.AutoReplyPrint;
import com.google.gson.Gson;
import com.qmuiteam.qmui.util.QMUIDisplayHelper;
import com.qmuiteam.qmui.widget.tab.QMUITabBuilder;
import com.qmuiteam.qmui.widget.tab.QMUITabIndicator;
import com.qmuiteam.qmui.widget.tab.QMUITabSegment;
import com.sun.jna.Pointer;
import com.sun.jna.ptr.LongByReference;
import com.vandin.weigher.sdk.connector.IWeigh;
import com.vandin.weigher.sdk.connector.IWeighCallback;
import com.vandin.weigher.sdk.connector.WeightData;
import com.vandin.weigher.sdk.weigher.WeightSerialPort;

import org.apache.tools.ant.types.resources.comparators.Content;

import my.AnimationTool;
import my.LogUtil;
import my.MathUtils;
import my.MySharedPreferences;
import my.SystemParamsUtils;
import my.TimeUtils;
import my.http.MyHttpListener;
import my.http.MyHttpUtils;
import my.http.MyParams;

public class PutPresenterImpl implements PutPresenter,IWeighCallback{

    private int mCurrentDialogStyle = com.qmuiteam.qmui.R.style.QMUI_Dialog;

    String oldWeight="0";
    String scaleWeight="0";  //真实的秤重量

    private IWeigh iWeigh;

    PutView scaleView;
    Context mContext;
    MySharedPreferences mSp;

    //静默拍照参数
    private boolean isSend = false;
    private Pointer h = Pointer.NULL;

    public PutPresenterImpl(PutView scaleView, Context context){
        this.mContext = context;
        this.scaleView = scaleView;
    }


    //----------------以下秤的接口------------------

    @Override
    public void onConnect(int status, String str, boolean b) {
        /**
         * status =1 ; str =正在连接……  ; b = true
         * status =2 ; str =连接成功    ; b = true
         * status =7 ; str =暂停读取    ; b = false
         * status =4 ; str =断开成功    ; b = true
         * status =10 ; str =读取重量    ; b = false           IControl.GetWeight();调用就会回调这个
         */
//        LogUtil.d("ScaleActivity==onConnect==status =="+ status);
//        LogUtil.d("ScaleActivity==onConnect==str =="+ str);
//        LogUtil.d("ScaleActivity==onConnect==b =="+ b);

        switch (status){
            case 2:
                iWeigh.GetWeight();
                break;
        }
    }

    @Override
    public void onReceiveData(String frame, String weight, boolean isSta) {
        //weight的格式 ====      +   0.515
        LogUtil.d("ScaleActivity==weight =="+ weight);
        if(weight.contains("-")){
            return;
        }
        if(oldWeight.equals(weight)){
            return;
        }else {
            oldWeight = weight;
        }
        try {
            scaleWeight =  UnitUtil.getNumByString(weight);
            scaleView.showWeight(Float.parseFloat(scaleWeight));
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
    }


    @Override
    public IWeigh getIWeigh() {
        if(mSp == null){
            mSp = new MySharedPreferences(mContext);
        }
        if (iWeigh != null) {
            iWeigh.disconnect();
        }
        WeightData weightData = new WeightData();
        weightData.setPort(mSp.getPort());
        weightData.setBaudrate(mSp.getBaudrate());
        iWeigh = new WeightSerialPort(mContext, this, weightData);
        iWeigh.OpenScaleUart();
        return iWeigh;
    }

    @Override
    public String getScaleWeight() {
        return scaleWeight;
    }

    @Override
    public void closeIWeigh() {
        if (iWeigh != null) {
            iWeigh.StopRead();
            iWeigh.disconnect();
            iWeigh = null;
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Override
    public void initLglLabel(TypeLabelGridLayout lglLabel) {
        lglLabel.setMulEnable(false);
        lglLabel.setColumnCount(7);
        lglLabel.setLabelBg(R.drawable.flow_popup);
        lglLabel.filterBeanListsAdd("商品类型", GreenDaoUtils.getGoodsTypeListBean().getAllName());
        lglLabel.filterBeanListsAdd("商品等级", GreenDaoUtils.getGoodsLevelListBean().getAllName());
        lglLabel.filterBeanListsAdd("商品年份", GreenDaoUtils.getGoodsTimeListBean().getAllName());
        lglLabel.setGridData(lglLabel.getFilterBeanLists());
    }

    public  void initTabSegment(MenuBean menuData, QMUITabSegment mTabSegment, ViewPager viewPager, View view_goods_menu){
        QMUITabBuilder tabBuilder = mTabSegment.tabBuilder();
        for (int i = 0; i < menuData.getChild().size(); i++) {
            mTabSegment.addTab(tabBuilder.setText(menuData.getChild().get(i).getSna()).build(mContext));
        }
        int space = QMUIDisplayHelper.dp2px(mContext, 16);
        mTabSegment.setIndicator(new QMUITabIndicator(
                QMUIDisplayHelper.dp2px(mContext, 2), false, true));
        mTabSegment.setMode(QMUITabSegment.MODE_SCROLLABLE);
        mTabSegment.setItemSpaceInScrollMode(space);
        mTabSegment.setupWithViewPager(viewPager, false);
        mTabSegment.setPadding(space, 0, space, 0);
        mTabSegment.addOnTabSelectedListener(new QMUITabSegment.OnTabSelectedListener() {
            @Override
            public void onTabSelected(int index) {
                AnimationTool.out(mContext,view_goods_menu);
            }

            @Override
            public void onTabUnselected(int index) {
            }

            @Override
            public void onTabReselected(int index) {
            }

            @Override
            public void onDoubleTap(int index) {
            }
        });
    }

    @Override
    public void settlement(String fsg,String type, FragmentActivity activity, GoodsListBean goodsListBean, SupplierListData supplier,String barCode) {
            if(!goodsListBean.haveRfid()){
                scaleView.printMessage("请输入RFID");
                return;
            }

            if(goodsListBean.haveRepeat()){
                scaleView.printMessage("请勿输入重复的箱码！");
                return;
            }

           goodsListBean.toComplete(fsg,activity,supplier,null,barCode);


            MyParams params = new MyParams();
            Gson gson = new Gson();
            String a = "";

            String url = "";
            if(Constants.BUY_IN.equals(type) || Constants.MAKE_IN.equals(type)|| Constants.PRODUCT_IN.equals(type)){
                url = Constants. URL_INSTOCK_INSERT;
            }else  if(Constants.MAKE_OUT.equals(type) || Constants.SALE_OUT.equals(type)){
                url = Constants.URL_OUTSTOCK_INSERT;

            }
             a = gson.toJson(goodsListBean.getList());
             params.putJson(a);

            MyHttpUtils.postJson(url, params, new MyHttpListener() {
                @Override
                public void onSuccess(int httpWhat, Object result) {
                    if(activity.isFinishing())return;
                    GoodsListBean resultData = (GoodsListBean) result;
                    toPrint(type,activity,goodsListBean,resultData);
                    scaleView.httpSuccess();
                }

                @Override
                public void onFailure(int httpWhat, Object result) {
                    if(activity.isFinishing())return;
//                super.onFailure(httpWhat, result);
                    if(result != null &&!TextUtils.isEmpty(((BasisBean) result).getStatusInfo())){
                        scaleView.printMessage(((BasisBean) result).getStatusInfo());
                    }else {
                        scaleView.printMessage("异常！");
                    }
                }

                @Override
                public void onFinish(int httpWhat) {

                }
            }, 0, GoodsListBean.class);

    }


    //----------------以下都是打印的接口------------------
        public void toPrint(String type,FragmentActivity  activity, GoodsListBean goodsListBean ,GoodsListBean resultData){
        new Thread(new Runnable() {
            @Override
            public void run() {
                Test_Pos_SampleTicket_58MM_1(type,activity,goodsListBean,resultData);
                scaleView.printFinish();
            }
        }).start();
    }


    private void Test_Pos_SampleTicket_58MM_1(String type ,FragmentActivity activity,GoodsListBean goodsListBean,GoodsListBean resultData) {
        Pointer h = OpenPort();
        if (h != Pointer.NULL) {

            AutoReplyPrint.INSTANCE.CP_Pos_ResetPrinter(h);
            AutoReplyPrint.INSTANCE.CP_Pos_SetMultiByteMode(h);
            AutoReplyPrint.INSTANCE.CP_Pos_SetMultiByteEncoding(h, AutoReplyPrint.CP_MultiByteEncoding_UTF8);


            AutoReplyPrint.INSTANCE.CP_Pos_SetAlignment(h, AutoReplyPrint.CP_Pos_Alignment_HCenter);
            AutoReplyPrint.INSTANCE.CP_Pos_SetTextScale(h, 1, 0);
            AutoReplyPrint.INSTANCE.CP_Pos_PrintText(h, ""+LoginBean.getInstance().getAname()+"\r\n");
            AutoReplyPrint.INSTANCE.CP_Pos_PrintText(h, ""+ type +"\r\n");
            AutoReplyPrint.INSTANCE.CP_Pos_PrintText(h, "————————————————\n");

            AutoReplyPrint.INSTANCE.CP_Pos_SetAlignment(h, AutoReplyPrint.CP_Pos_Alignment_Left);
            AutoReplyPrint.INSTANCE.CP_Pos_SetTextScale(h, 0, 0);
            AutoReplyPrint.INSTANCE.CP_Pos_PrintText(h, "秤编号:  "+ SystemParamsUtils.getAndroidID(activity)+"\n");
//            AutoReplyPrint.INSTANCE.CP_Pos_PrintText(h, "凭证号:  "+submitBean.getTid()+"\n");
            AutoReplyPrint.INSTANCE.CP_Pos_PrintText(h, "日期:  "+ TimeUtils.getCurrentTimeByFormat(TimeUtils.TIME_FOMART_DAY)+"\n");
            if(Constants.BUY_IN.equals(type)){
                AutoReplyPrint.INSTANCE.CP_Pos_PrintText(h, "供应商:  "+ goodsListBean.getCna()+"\n");
                AutoReplyPrint.INSTANCE.CP_Pos_PrintText(h, "身份证:  "+ goodsListBean.getCno()+"\n");
            }else if(Constants.SALE_OUT.equals(type)){
                AutoReplyPrint.INSTANCE.CP_Pos_PrintText(h, "客户:  "+ goodsListBean.getCna()+"\n");
                AutoReplyPrint.INSTANCE.CP_Pos_PrintText(h, "身份证:  "+ goodsListBean.getCno()+"\n");
            }


            AutoReplyPrint.INSTANCE.CP_Pos_PrintText(h, "--------------------------------\n");


            for (GoodsListData goodsData : goodsListBean.getList()){
                AutoReplyPrint.INSTANCE.CP_Pos_PrintText(h, "箱码:  "+ goodsData.getRfid()+"\n");
                AutoReplyPrint.INSTANCE.CP_Pos_PrintText(h, "品名:  "+ goodsData.getGna()+"\n");
                AutoReplyPrint.INSTANCE.CP_Pos_PrintText(h, "净重:  "+ goodsData.getGwt()+"斤"+"\n");
                if(MyUtils.getHomeSelectName().contains("饼")){
                    AutoReplyPrint.INSTANCE.CP_Pos_PrintText(h, "数量:  "+ goodsData.getGnu()+"\n");
                }

                if(Constants.SALE_OUT.equals(type) || Constants.BUY_IN.equals(type)){
                    AutoReplyPrint.INSTANCE.CP_Pos_PrintText(h, "单价:  "+ goodsData.getPri()+"元"+"\n");
                    AutoReplyPrint.INSTANCE.CP_Pos_PrintText(h, "金额:  "+ MathUtils.multiply(goodsData.getGwt(),goodsData.getPri())+"元"+"\n");
                }
               AutoReplyPrint.INSTANCE.CP_Pos_PrintText(h, "--------------------------------\n");
            }

            if(Constants.SALE_OUT.equals(type) || Constants.BUY_IN.equals(type)){
                AutoReplyPrint.INSTANCE.CP_Pos_PrintText(h, "金额合计:  "+ goodsListBean.getAllTotal()+"元"+"\n");
                AutoReplyPrint.INSTANCE.CP_Pos_PrintText(h, "重量合计:  "+ goodsListBean.getAllWeight()+"斤"+"\n");
            }


            AutoReplyPrint.INSTANCE.CP_Pos_PrintText(h, "操作员  :"+ LoginBean.getInstance().getUname()+"\n");

            AutoReplyPrint.INSTANCE.CP_Pos_PrintText(h, "    \r\n");

            AutoReplyPrint.INSTANCE.CP_Pos_SetBarcodeUnitWidth(h, 2);
            AutoReplyPrint.INSTANCE.CP_Pos_SetBarcodeHeight(h, 60);
            AutoReplyPrint.INSTANCE.CP_Pos_SetBarcodeReadableTextFontType(h, 0);
            AutoReplyPrint.INSTANCE.CP_Pos_SetBarcodeReadableTextPosition(h, AutoReplyPrint.CP_Pos_BarcodeTextPrintPosition_BelowBarcode);
            AutoReplyPrint.INSTANCE.CP_Pos_PrintBarcode(h, AutoReplyPrint.CP_Pos_BarcodeType_CODE93, ""+resultData.getMid());



            AutoReplyPrint.INSTANCE.CP_Pos_PrintText(h, "    \r\n");
            AutoReplyPrint.INSTANCE.CP_Pos_PrintText(h, "    \r\n");
            AutoReplyPrint.INSTANCE.CP_Pos_PrintText(h, "    \r\n");
            AutoReplyPrint.INSTANCE.CP_Pos_PrintText(h, "    \r\n");

            AutoReplyPrint.INSTANCE.CP_Pos_Beep(h, 1, 500);

            QueryPrintResult(h);
            AutoReplyPrint.INSTANCE.CP_Port_Close(h);
        }
    }

    private Pointer OpenPort() {
        Pointer h = Pointer.NULL;
        h = AutoReplyPrint.INSTANCE.CP_Port_OpenUsb("VID:0x4B43,PID:0x3538", 1);

        if (h == Pointer.NULL) {
            scaleView.printMessage("OpenPort Failed");
        }
        return h;
    }

    private void ClosePort() {
        if (h != Pointer.NULL) {
            AutoReplyPrint.INSTANCE.CP_Port_Close(h);
            h = Pointer.NULL;
        }
    }

    private boolean QueryPrintResult(Pointer h) {
        boolean result = AutoReplyPrint.INSTANCE.CP_Pos_QueryPrintResult(h, 30000);
//        scaleView.printMessage(result ? "Print Success" : "Print Failed");
        scaleView.printMessage(result ? "打印成功" : "打印失败");
        if (!result) {
            LongByReference printer_error_status = new LongByReference();
            LongByReference printer__info_status = new LongByReference();
            LongByReference timestamp_ms_printer_status = new LongByReference();
            if (AutoReplyPrint.INSTANCE.CP_Printer_GetPrinterStatusInfo(h, printer_error_status, printer__info_status, timestamp_ms_printer_status)) {
                AutoReplyPrint.CP_PrinterStatus status = new AutoReplyPrint.CP_PrinterStatus(printer_error_status.getValue(), printer__info_status.getValue());
                String error_status_string = String.format("Printer Error Status: 0x%04X", printer_error_status.getValue() & 0xffff);
                if (status.ERROR_OCCURED()) {
                    if (status.ERROR_CUTTER())
                        error_status_string += "[ERROR_CUTTER]";
                    if (status.ERROR_FLASH())
                        error_status_string += "[ERROR_FLASH]";
                    if (status.ERROR_NOPAPER())
                        error_status_string += "[ERROR_NOPAPER]";
                    if (status.ERROR_VOLTAGE())
                        error_status_string += "[ERROR_VOLTAGE]";
                    if (status.ERROR_MARKER())
                        error_status_string += "[ERROR_MARKER]";
                    if (status.ERROR_ENGINE())
                        error_status_string += "[ERROR_ENGINE]";
                    if (status.ERROR_OVERHEAT())
                        error_status_string += "[ERROR_OVERHEAT]";
                    if (status.ERROR_COVERUP())
                        error_status_string += "[ERROR_COVERUP]";
                    if (status.ERROR_MOTOR())
                        error_status_string += "[ERROR_MOTOR]";
                }
                scaleView.printMessage(error_status_string);
            } else {
                scaleView.printMessage("CP_Printer_GetPrinterStatusInfo Failed");
            }
        }
        return result;
    }




}
